package com.legendshop.oa.security;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.util.UrlUtils;

import com.legendshop.oa.constants.Constants;


public class FailureUrlRedirectStrategy  implements RedirectStrategy{

	private boolean contextRelative;

	// HttpSessionRequestCache
	static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";

	/**
	 * Redirects the response to the supplied URL.
	 * <p>
	 * If <tt>contextRelative</tt> is set, the redirect value will be the value
	 * after the request context path. Note that this will result in the loss of
	 * protocol information (HTTP or HTTPS), so will cause problems if a
	 * redirect is being performed to change to HTTPS, for example.
	 */
	public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
		String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
		redirectUrl = response.encodeRedirectURL(redirectUrl);

		DefaultSavedRequest savedRequest = (DefaultSavedRequest) request.getSession().getAttribute(SAVED_REQUEST);
		if (savedRequest != null) {
			redirectUrl = appendUrl(redirectUrl, savedRequest.getRequestURL());
		}

		response.sendRedirect(redirectUrl);
	}

	private String calculateRedirectUrl(String contextPath, String url) {
		if (!UrlUtils.isAbsoluteUrl(url)) {
			if (contextRelative) {
				return url;
			} else {
				return contextPath + url;
			}
		}

		// Full URL, including http(s)://

		if (!contextRelative) {
			return url;
		}

		// Calculate the relative URL from the fully qualified URL, minus the
		// last
		// occurrence of the scheme and base context.
		url = url.substring(url.lastIndexOf("://") + 3); // strip off scheme
		url = url.substring(url.indexOf(contextPath) + contextPath.length());

		if (url.length() > 1 && url.charAt(0) == '/') {
			url = url.substring(1);
		}

		return url;
	}

	private String appendUrl(String url, String returnUrl) {
		String newUrl = url;
		if (url.endsWith("/")) {
			newUrl = url.substring(0, url.length() - 1);
		}
		String returnUrl1 = null;
		try {
			returnUrl1 = URLEncoder.encode(returnUrl, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (newUrl.indexOf("?") > 0) {
			return newUrl + "&" + Constants.RETURN_URL + "=" + returnUrl1;
		} else {
			return newUrl + "?" + Constants.RETURN_URL + "=" + returnUrl1;
		}
	}

	/**
	 * If <tt>true</tt>, causes any redirection URLs to be calculated minus the
	 * protocol and context path (defaults to <tt>false</tt>).
	 */
	public void setContextRelative(boolean useRelativeContext) {
		this.contextRelative = useRelativeContext;
	}
}
